import express from 'express';
import user from './routes/user';
import sign from './routes/sign';
import wx from './routes/wx';
import logger from './config/log4jsConfig';
import log4js from 'log4js';
import bodyParser from 'body-parser';
import cors from 'cors';
import path from 'path';
global.app = express();

// 重写console.log方法，调用日志打印
console.log = text => {
	const info = logger.info.bind(logger);
	info('JS-console.log');
	info(text);
	process.env.DEV === 'true' && console.info(text);
};

// 封装返回拦截，增加打印日志
global.baseResponse = (req, res, data) => {
	let resLog = `response___req.url:::${req.url}---`;
	resLog += `req.headers:::${JSON.stringify(req.headers)}`;
	resLog += `---res:::${JSON.stringify(data)}`;
	res.send(JSON.stringify(data));
	console.log(resLog);
};

app.use(log4js.connectLogger(logger, { level: 'auto' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

try {
	app.all('*', async (req, res, next) => {
		// 允许跨域
		res.header('Access-Control-Allow-Origin', '*');
		res.header('Access-Control-Allow-Credentials', true);
		res.header(
			'Access-Control-Allow-Headers',
			'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
		);
		res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
		// 让options请求快速返回
		req.method == 'OPTIONS' ? res.send(200) : next();
	});

	// 全局的token拦截
	app.use(async (req, res, next) => {
		try {
			let resObj = '';
			// 打印request log
			let reqLog = `request___req.url::: ${req.url}---req.headers:::`;
			reqLog += `${JSON.stringify(req.headers)}`;
			reqLog += `---res:::${resObj}`;
			console.log(reqLog);
			resObj ? res.send(resObj) : next();
		} catch (error) {
			console.log(error);
			res.send(JSON.stringify({ code: -1, message: error.message }));
		}
	});

	/**
	 * admin路由
	 */
	app.use('/api', user);
	app.use('/api', sign);
	app.use('/api', wx);
} catch (error) {
	console.log(error);
}

app.listen(3000, () => {
	console.log(`listen to port 3000`);
});

process.on('uncaughtException', function(err) {
	console.log('ERROR:::uncaughtException');
	console.log(err);
});

process.on('unhandledRejection', (error, promise) => {
	console.log('ERROR:::unhandledRejection');
	console.log(error);
	console.log(promise);
});
